package middleware

import (
	"bytes"
	"github.com/gin-gonic/gin"
	"time"
	"xinduobang/stock/utils"
)

func GetQueryParams(c *gin.Context) map[string]any {
	query := c.Request.URL.Query()
	var queryMap = make(map[string]any, len(query))
	for k := range query {
		queryMap[k] = c.Query(k)
	}
	//c.Request.Body.Read(&queryMap)
	return queryMap
}

//func GetPostBody(c *gin.Context) () {
//	c.Request.Header.Get("Content-Length")
//}

// LoggerMiddleware 日志中间件
func ZapLoggerMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Header("Machine", getMatchine())
		// 开始时间
		timeBegin := time.Now().UnixNano()
		// 处理请求
		//log.Println("✅ log start")

		// 需要放到next前面否则最后就是空了
		writer := responseWriter{
			c.Writer,
			bytes.NewBuffer([]byte{}),
		}
		c.Writer = writer

		c.Next()
		//log.Println("✅ log end")
		// 结束时间
		timeEnd := time.Now().UnixNano()

		// 计算请求处理时间
		timeCost := float64(timeEnd-timeBegin) / 1e9 * 1000

		// logger 支持结构化的
		//log.Info(zap.String("method", c.Request.Method),
		//	zap.String("path", c.Request.URL.Path),
		//	zap.Float64("time_cost", timeCost),
		//	zap.Int("status", c.Writer.Status()),
		//	zap.String("ip", c.ClientIP()),
		//	zap.String("user_agent", c.Request.UserAgent()),
		//	zap.String("request_id", c.Writer.Header().Get("X-Request-Id")),
		//	zap.String("fxg", "🟦"),
		//)
		utils.Info(c, map[string]interface{}{
			"method":        c.Request.Method,
			"path":          c.Request.URL.Path,
			"req_method":    c.Request.Method,
			"req_params":    GetQueryParams(c),
			"req_headers":   c.Request.Header,
			"req_post_body": c.Request.PostForm,

			"ip":            c.ClientIP(),
			"user_agent":    c.Request.UserAgent(),
			"time_cost":     timeCost,
			"status":        c.Writer.Status(),
			"size":          c.Writer.Size(),
			"response_body": writer.b.String(),
			"rep_head":      writer.Header(),
		}, " ✅")
		// 记录日志
		utils.Info(c, "🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟩 结束 🟩🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦🟦")

	}
}
